package com.cmcc.aregister.cs.database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.cmcc.aregister.cs.cache.AutoAppointTipCache;
import com.cmcc.aregister.cs.cache.Cache;
import com.cmcc.aregister.cs.cache.HaoyuanTipCache;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.util.DBUtils;
import com.cmcc.aregister.cs.util.MyLogger;
import com.cmcc.aregister.cs.util.Utils;

/**
 * IDatabase的实现
 * 
 * @author swq
 * 
 */
public class DatabaseImpl implements IDatabase {
	private DBUtils db = null;
	private static final MyLogger logger = MyLogger.getLogger();
	private static IDatabase database;

	private DatabaseImpl(Context app) {
		db = new DBUtils(app);
		db.open();
	}

	public static IDatabase getInstance(Context app) {
		if (database == null) {
			database = new DatabaseImpl(app);
		}
		return database;
	}

	public void closeDataBase() {
		if (db != null) {
			synchronized (db) {
				db.close();
			}
		}
	}

	@Override
	public boolean deleteHttpCache(String url) {
		if (url == null) {
			return false;
		}
		try {
			return db.delete(Cache.TABLE_NAME, Cache.URL + "='" + url + "'");
		} catch (Exception e) {
			return false;
		} finally {
		}
	}

	@Override
	public Object queryHttpCache(String url) {
		Cursor cursor = null;
		try {
			cursor = db.query(Cache.TABLE_NAME, new String[] { Cache.URL,
					Cache.CACHEMAP, Cache.CACHETIME }, Cache.URL + "='" + url
					+ "'");
			if (cursor.getCount() > 0) {
				@SuppressWarnings("unchecked")
				Map<String, Object> objMap = (HashMap<String, Object>) Utils
						.serialOut(cursor.getBlob(1));
				String cacheUpdateTime = cursor.getString(2);
				objMap.put(Arguments.CACHE_TIME, cacheUpdateTime);
				return objMap;
			} else {
				return null;
			}

		} catch (Exception e) {
			logger.e(e);
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	@Override
	public synchronized boolean saveOrupdateHttpCache(String url,
			ContentValues contentValues) {
		Cursor cursor = null;
		try {
			cursor = db.query(Cache.TABLE_NAME, null, "url" + "='" + url + "'");
			if (cursor != null && cursor.getCount() > 0) {
				return db.update(Cache.TABLE_NAME, "url" + "='" + url + "'",
						contentValues);
			} else {
				return db.insert(Cache.TABLE_NAME, contentValues) != -1;
			}
		} catch (Exception e) {
			logger.e(e);
			return false;
		} finally {
			if (cursor != null)
				cursor.close();
		}
	}

	/**
	 * 删除缓存
	 */
	public void deleteOutTimeCache() {
		// long time = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
		long time = 0;
		try {
			db.delete(Cache.TABLE_NAME, Cache.CACHETIME + " > '" + time + "'");
		} catch (Exception e) {
			logger.e(e);
		} finally {
		}
	}

	@Override
	public synchronized boolean saveOrupdateAutoCache(String id,
			ContentValues contentValues) {
		Cursor cursor = null;
		try {
			cursor = db.query(AutoAppointTipCache.TABLE_NAME, null, "tipInfoId"
					+ "='" + id + "'");
			if (cursor != null && cursor.getCount() > 0) {
				return db.update(AutoAppointTipCache.TABLE_NAME, "tipInfoId"
						+ "='" + id + "'", contentValues);
			} else {
				return db.insert(AutoAppointTipCache.TABLE_NAME, contentValues) != -1;
			}
		} catch (Exception e) {
			logger.e(e);
			return false;
		} finally {
			if (cursor != null)
				cursor.close();
		}
	}

	@Override
	public Object queryAutoCache(String id) {
		Cursor cursor = null;
		try {
			cursor = db.query(AutoAppointTipCache.TABLE_NAME, new String[] {
					AutoAppointTipCache.TIPINFOID, AutoAppointTipCache.PHONE,
					AutoAppointTipCache.TIME }, AutoAppointTipCache.TIPINFOID
					+ "='" + id + "'");
			if (cursor.getCount() > 0) {
				Map<String, Object> objMap = new HashMap<String, Object>();
				String tipInfoId = cursor.getString(0);
				String phone = cursor.getString(1);
				String time = cursor.getString(2);
				objMap.put("id", tipInfoId);
				objMap.put("phone", phone);
				objMap.put("time", time);
				return objMap;
			} else {
				return null;
			}

		} catch (Exception e) {
			logger.e(e);
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	@Override
	public synchronized boolean saveHaoyuanTipCache(ContentValues contentValues) {
		try {
			return db.insert(HaoyuanTipCache.TABLE_NAME, contentValues) != -1;
		} catch (Exception e) {
			logger.e(e);
			return false;
		}
	}

	@Override
	public Object queryHaoyuanTipCache(String phone) {
		Cursor cursor = null;
		try {
			cursor = db.queryAllByOrderByAndWhere(HaoyuanTipCache.TABLE_NAME,
					new String[] { HaoyuanTipCache.START_TIME,
							HaoyuanTipCache.PHONE, HaoyuanTipCache.HOS_NAME,
							HaoyuanTipCache.DEP_NAME, HaoyuanTipCache.DOC_NAME,
							HaoyuanTipCache.ID }, HaoyuanTipCache.START_TIME,
					HaoyuanTipCache.PHONE + "='" + phone + "'");
			ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			while (cursor.moveToNext()) {
				HashMap<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < cursor.getColumnCount(); i++) {
					String startTime = cursor.getString(0);
					String phoneNum = cursor.getString(1);
					String hosName = cursor.getString(2);
					String depName = cursor.getString(3);
					String docName = cursor.getString(4);
					String id = cursor.getString(5);
					map.put("startTime", startTime);
					map.put("phone", phoneNum);
					map.put("hosName", hosName);
					map.put("depName", depName);
					map.put("docName", docName);
					map.put("id", id);
				}
				list.add(map);
			}
		return list;
		} catch (Exception e) {
			logger.e(e);
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * 删除号源提醒缓存
	 */
	public void deleteHaoyuanTipCache(String id) {
		try {
			db.delete(HaoyuanTipCache.TABLE_NAME, HaoyuanTipCache.ID + " ='"
					+ id + "'");
		} catch (Exception e) {
			logger.e(e);
		} finally {
		}
	}

	/**
	 * 根据号源提醒任务ID删除缓存
	 */
	@Override
	public void deleteHaoyuanTipCacheById(String id) {
		Cursor cursor = null;
		try {
			cursor = db.query(HaoyuanTipCache.TABLE_NAME,
					new String[] { HaoyuanTipCache.TASK_ID },
					HaoyuanTipCache.TASK_ID + "='" + id + "'");
			if (cursor.getCount() > 0) {
				db.delete(HaoyuanTipCache.TABLE_NAME, HaoyuanTipCache.TASK_ID
						+ " ='" + id + "'");
			}
		} catch (Exception e) {
			logger.e(e);
		} finally {
			if (cursor != null)
				cursor.close();
		}
	}
}
